//
//  InsuranceInfoController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/7/11.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON
class InsuranceInfoController: BaseController {
    var flag = 0//标识图片
    var pic5 = "",pic6 = "",pic7 = "" ,pic8 = "",pic9 = "",pic10 = ""
    var insuranceInfo:InsuranceModel!
    var insuInfoTable:UITableView!//数据表格
    var insuInfoCell:InsuranceInfoCell!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupNavBar(title: "保险办理", isback: true, appearWay: 3, isright: false)//自定义导航
        if reachability.isReachable {
            getInsurance()
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
        //初始化表格
        insuInfoTable = UITableView(frame: CGRect(x:0,y:kStatusBarH + kNavigationBarH,width:kScreenW,height:kScreenH - kStatusBarH - kNavigationBarH),style: UITableViewStyle.plain)
        insuInfoTable?.delegate = self
        insuInfoTable?.dataSource = self
        insuInfoTable?.separatorStyle = UITableViewCellSeparatorStyle.none
        insuInfoTable?.rowHeight = 7*oTop + 2*oLabelH + 4*oImgH + remarkH + cellH + 10
        if "1" == insuranceInfo.isOriginals {//上传车身照
            insuInfoTable?.rowHeight = 15*oTop + 8*oLabelH + 10*oImgH + 2*cellH + remarkH + 10
        }
        if "0" == insuranceInfo.isOriginals {//不需要车身照 {
            insuInfoTable?.rowHeight = 9*oTop + 2*oLabelH + 4*oImgH + remarkH + 2*cellH + 10
        }
        self.view.addSubview(insuInfoTable)
    }
}
extension InsuranceInfoController{
    //查询审车详情
    func getInsurance(){
        let urlString = "\(projectUrl)/order/other/carinsurance/\(insuranceInfo.orderNo)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
        Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                if json["success"] == true {
                    self.insuranceInfo = InsuranceModel.init(dict: json["rdata"])
                    self.insuInfoTable.reloadData()
                }else{
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }else{
                print(response.result.error!) //输出错误日志
            }
        }
    }
    //选择操作方式 支付，抢单，完成订单？
    func operatorFun(sender: UIButton){
        if 0 == sender.tag {//去支付
            if insuranceInfo.driveLicense_5.isEmpty {//车身照如果需要都必填，故判断其中一个即可
                if "" == self.pic5 || "" == self.pic6 || "" == self.pic7 || "" == self.pic8 || "" == self.pic9 || "" == self.pic10 {
                    checkAlertFun(message: "请上传车身照片！")
                }else{
                    updateCarPic()
                }
            }else{
                let pc = PayController()
                pc.orderID = self.insuranceInfo.orderNo
                pc.totalAmount = self.insuranceInfo.samount
                pc.modelType = "carinsurance"
                self.present(pc, animated: true, completion: nil)
            }
        }else if(1 == sender.tag){//去抢单
            let urlString = "\(projectUrl)/order/other/accept/carinsurance/\(insuranceInfo.orderNo)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            toOperatOrder(url: urlString)
        }
        else if(2 == sender.tag){//去完成订单
            let urlString = "\(projectUrl)/order/other/finish/carinsurance/\(insuranceInfo.orderNo)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            toOperatOrder(url: urlString)
        }
    }
    //提交车身照
    func updateCarPic() {
        if reachability.isReachable {
            let parameter:[String:Any] = [
                "orderData":"{\"driveLicense_5\":\"\(self.pic5)\",\"driveLicense_6\":\"\(self.pic6)\",\"driveLicense_7\":\"\(self.pic7)\",\"driveLicense_8\":\"\(self.pic8)\",\"driveLicense_9\":\"\(self.pic9)\",\"driveLicense_10\":\"\(self.pic10)\"}"
            ]
            let urlString = "\(projectUrl)/order/other/update/carinsurance/\(insuranceInfo.orderNo)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
            Alamofire.request(urlString, method: .get, parameters: parameter, headers : headers).responseJSON { (response) in
                if response.result.isSuccess{
                    let json = JSON(response.result.value as! [String : AnyObject])
                    if json["success"] == true {//上传成功后直接去付款
                        let pc = PayController()
                        pc.orderID = self.insuranceInfo.orderNo
                        pc.totalAmount = self.insuranceInfo.samount
                        pc.modelType = "carinsurance"
                        self.present(pc, animated: true, completion: nil)
                    }else{
                        self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                    }
                }else{
                    print(response.result.error!) //输出错误日志
                }
            }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //选择上传图片
    func choicePicture(sender: UIButton) {
        self.flag = sender.tag
        centerY = sender.convert(sender.bounds, to: toast.container).origin.y
        let alert = UIAlertController()
        let cleanAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel,handler:nil)
        let photoAction = UIAlertAction(title: "拍照", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.cameraFunc()
        }
        let choseAction = UIAlertAction(title: "从手机相册选择", style: UIAlertActionStyle.default){ (action:UIAlertAction)in
            self.photoFunc()
        }
        alert.addAction(cleanAction)
        alert.addAction(photoAction)
        alert.addAction(choseAction)
        self.present(alert, animated: true, completion: nil)
    }
    //调用相机
    func cameraFunc(){
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.camera
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: nil)
        }else{
            print("读取相册失败")
        }
    }
    //调用相册
    func photoFunc(){
        //初始化图片控制器
        let picker = UIImagePickerController()
        //设置代理
        picker.delegate = self
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            //指定图片控制器类型
            picker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            //弹出控制器，显示界面
            self.present(picker, animated: true, completion: nil)
        }else{
            print("读取相册失败")
        }
    }
}
extension InsuranceInfoController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //选择图片成功后代理
    func imagePickerController(_ picker: UIImagePickerController,
                               didFinishPickingMediaWithInfo info: [String : Any]) {
        //显示的图片
        let image:UIImage =  info[UIImagePickerControllerOriginalImage] as! UIImage
        if reachability.isReachable {
            uploadCarAuditImage(img: image)//上传图片到服务器
            picker.dismiss(animated: true, completion: nil)//图片控制器退出
            toast.showLoadingView(x: oImgLeft + oImgW + 10, y: centerY)
        }else{
            let alertController = UIAlertController(title: alertTitle, message: netNotice, preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //上传图片
    func uploadCarAuditImage(img:UIImage){
        let toUrl = "\(projectUrl)/file/upload/carinsurance/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
        let imageData = UIImageJPEGRepresentation(img, 1.0)!
        //使用Alamofire上传
        Alamofire.upload(multipartFormData: { (mult) in
            mult.append(imageData, withName: "file", fileName: "carinsurance\(self.flag).png", mimeType: "image/png")
        }, to: toUrl, encodingCompletion: { (result) in
            switch result {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    let jsonString = response.result.value!
                    let jsonDate = JSON(jsonString)
                    if jsonDate["success"] == true {
                        let photoID = jsonDate["rdata"].rawValue as! String
                        if(5 == self.flag){
                            self.pic5 = photoID
                            self.insuInfoCell.driveLicense_5.setImage(img, for: .normal)
                        }
                        if(6 == self.flag){
                            self.pic6 = photoID
                            self.insuInfoCell.driveLicense_6.setImage(img, for: .normal)
                        }
                        if(7 == self.flag){
                            self.pic7 = photoID
                            self.insuInfoCell.driveLicense_7.setImage(img, for: .normal)
                        }
                        if(8 == self.flag){
                            self.pic8 = photoID
                            self.insuInfoCell.driveLicense_8.setImage(img, for: .normal)
                        }
                        if(9 == self.flag){
                            self.pic9 = photoID
                            self.insuInfoCell.driveLicense_9.setImage(img, for: .normal)
                        }
                        if(10 == self.flag){
                            self.pic10 = photoID
                            self.insuInfoCell.driveLicense_10.setImage(img, for: .normal)
                        }
                    }else{
                        self.failOperNoticeFun(code: jsonDate["rcode"].rawString()!, message: jsonDate["rdata"].rawString()!)
                    }
                    toast.closeWin()
                }
            case .failure(let encodingError):
                print("ERROR RESPONSE: \(encodingError)")
            }
        })
    }
}
extension InsuranceInfoController:UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        insuInfoCell = tableView.dequeueReusableCell(withIdentifier: "insuInfoCellID") as? InsuranceInfoCell
        if insuInfoCell == nil {
            insuInfoCell = InsuranceInfoCell(style: UITableViewCellStyle.default,reuseIdentifier: "insuInfoCellID")
        }
        insuInfoCell.configCellDateWithModel(insuranceInfo)
        return insuInfoCell!
    }
}
